"""
完全重新实现的干净游戏板类，避免所有潜在问题
"""
from typing import List, Tuple, Optional

from tetris.constants import BOARD_WIDTH, BOARD_HEIGHT
from tetris.tetromino import Tetromino


class CleanBoard:
    """完全重写的游戏板类，确保没有显示错误的方块"""
    
    def __init__(self):
        """初始化一个保证为空的游戏板"""
        # 创建一个真正空的游戏板
        self.grid = [[None for _ in range(BOARD_WIDTH)] for _ in range(BOARD_HEIGHT)]
        
        # 游戏状态
        self.score = 0
        self.level = 1
        self.lines_cleared = 0
        
        print("使用干净板实现")
    
    def is_valid_position(self, tetromino: Tetromino) -> bool:
        """检查方块是否在有效位置"""
        for x, y in tetromino.get_coords():
            # 检查左右边界
            if x < 0 or x >= BOARD_WIDTH:
                return False
            
            # 检查底部边界
            if y >= BOARD_HEIGHT:
                return False
            
            # 检查是否与已有方块重叠（只检查在游戏板内的部分）
            if y >= 0 and self.grid[y][x] is not None:
                return False
                
        return True
    
    def add_tetromino(self, tetromino: Tetromino) -> None:
        """将方块添加到游戏板上"""
        print(f"添加方块: {tetromino.shape_type} 在位置 ({tetromino.x}, {tetromino.y})")
        for x, y in tetromino.get_coords():
            if 0 <= y < BOARD_HEIGHT and 0 <= x < BOARD_WIDTH:
                self.grid[y][x] = tetromino.color
    
    def clear_lines(self) -> int:
        """清除已填满的行并返回清除的行数"""
        lines_cleared = 0
        y = BOARD_HEIGHT - 1
        
        while y >= 0:
            # 检查当前行是否已填满
            if all(cell is not None for cell in self.grid[y]):
                lines_cleared += 1
                
                # 将上面的所有行下移
                for y2 in range(y, 0, -1):
                    self.grid[y2] = self.grid[y2 - 1].copy()
                
                # 创建新的空行
                self.grid[0] = [None for _ in range(BOARD_WIDTH)]
            else:
                y -= 1
        
        # 更新分数和级别
        if lines_cleared > 0:
            self.score += lines_cleared * lines_cleared * 100
            self.lines_cleared += lines_cleared
            self.level = (self.lines_cleared // 10) + 1
            
        return lines_cleared
    
    def is_game_over(self) -> bool:
        """检查游戏是否结束"""
        # 只检查第三行以下，避免误判
        return any(cell is not None for cell in self.grid[3]) 